# -*- coding:utf-8 -*-
import paho.mqtt.client as mqtt
from nameko.standalone.rpc import ClusterRpcProxy
import schedule
import threading
import json
import time

config = {
    'AMQP_URI': "amqp://guest:guest@127.0.0.1"
}

#global client
global reportthread


# 连接MQTT服务器
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("TSQ_CTRL/tsinghua_#0001")
    client.subscribe("TSQ_CTRL/tsinghua_#0002")


# 消息处理函数
def on_message(client, userdata, msg):
    print("主题:"+msg.topic+" 消息:"+str(msg.payload))
    re_msg = {"time_tamp": "2019-03-22 13:43:48",
              "dev_id": "tsinghua_#0001",
              "succeed": True,
              "message": "str"
              }
    time_stamp = time.time()
    re_msg["time_tamp"] = time.strftime('%Y-%m-%d %H:%M:%S', time_stamp)
    if msg.topic=="TSQ_CTRL/tsinghua_#0001":
        re_msg["dev_id"] = "tsinghua_#0001"
        with ClusterRpcProxy(config) as cluster_rpc:
            command = json.loads(msg.payload)
            # {
            #     "circuit breaker": true
            # }
            hdatas = cluster_rpc.modbus_service.control_in_time.call_async(command)
            data = hdatas.result()
    elif msg.topic=="TSQ_CTRL/tsinghua_#0002":
        re_msg["dev_id"] = "tsinghua_#0002"
        with ClusterRpcProxy(config) as cluster_rpc:
            command = json.loads(msg.payload)
            # {
            #     "circuit breaker": true
            # }
            hdatas = cluster_rpc.modbus_service.control_in_time.call_async(command)
            data = hdatas.result()

    client.publish(topic="TSQ_UP_CTRL", payload=json.dumps(re_msg), qos=2)


def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection.")
    reportthread.cancel()


def report_timely(client=None):
    def run():
        with ClusterRpcProxy(config) as cluster_rpc:
            hdatas = cluster_rpc.modbus_service.get_realtime_data.call_async()
            data = hdatas.result()
            print(data)
            msg = {"time_tamp": "2019-03-22 13:43:48",
                   "data": [{
                       "dev_id": "tsinghua_#0001",
                       "u": 66.00,
                       "i": 66.00,
                       "p": 66.00,
                       "q": 66.00,
                       "s": 66.00,
                       "pf": 66.00,
                       "fr": 66.00,
                       "temp": 66.00,
                       "flag_1": True,
                       "flag_2": True,
                       "flag_3": True,
                       "flag_4": True
                      },
                      {
                       "dev_id": "tsinghua_#0002",
                       "u": 66.00,
                       "i": 66.00,
                       "p": 66.00,
                       "q": 66.00,
                       "s": 66.00,
                       "pf": 66.00,
                       "fr": 66.00,
                       "temp": 66.00,
                       "flag_1": True,
                       "flag_2": True,
                       "flag_3": True,
                       "flag_4": True
                      }]
                   }
            try:
                client.publish(topic='TSQ_UP', payload=json.dumps(msg), qos=2)
            except:
                pass
            reportthread = threading.Timer(5, run)
            reportthread.start()

    reportthread = threading.Timer(5, run)
    reportthread.start()


def start():
    client = mqtt.Client()
    from Common.settings import MQTTBASE
    '''
    trust = "C:/Python27/pom/root_cert.pem" #开启TLS时的认证文件目录
    user = "smart-sensor/ldw"
    pwd = "O7hrHKUYJLqxwajP/5/2fqdZ8KIDZ/aR4/CWrmRt6Gg="

    client.tls_insecure_set(True) #检查hostname的cert认证
    client.tls_set(trust) #设置认证文件
    client.username_pw_set(user, pwd) #设置用户名，密码
    '''
    client.on_connect = on_connect  # 设置连接上服务器回调函数
    client.on_message = on_message  # 设置接收到服务器消息回调函数
    client.on_disconnect = on_disconnect
    client.connect(MQTTBASE['MQTTHOST'], MQTTBASE['MQTTPORT'], 60)  # 连接服务器,端口为1883,维持心跳为60秒
    report_timely(client=client)
    client.loop_forever()


if __name__ == '__main__':
    start()